import React, { useMemo, useRef, useEffect, useState } from 'react';
import { Input, Button, Empty } from 'antd';
import { SendOutlined, StopOutlined, CustomerServiceOutlined } from '@ant-design/icons';
import { useChatStream } from './hooks/useChatStream';
import AssistantMessage from './components/AssistantMessage';
import UserMessage from './components/UserMessage';
import './styles.css';

interface AssistantTabProps {
  unitId: string;
}

const AssistantTab: React.FC<AssistantTabProps> = ({ unitId }) => {
  const { messages, isStreaming, sendMessage, stopStreaming } = useChatStream(unitId);
  const [input, setInput] = useState('');
  const listRef = useRef<HTMLDivElement>(null);

  const handleSend = () => {
    const text = input.trim();
    if (!text) return;
    sendMessage(text);
    setInput('');
  };

  useEffect(() => {
    // 滚动到底部
    if (listRef.current) {
      listRef.current.scrollTop = listRef.current.scrollHeight;
    }
  }, [messages]);

  return (
    <div className="assistant-container">
      <div className="header">
        <div className="title">
          <CustomerServiceOutlined style={{ color: '#1677ff' }} />
          <span>智能助手</span>
        </div>
      </div>

      <div className="message-list" ref={listRef}>
        {messages.length === 0 ? (
          <div className="empty-container">
            <Empty description="开始与智能助手对话吧" />
          </div>
        ) : (
          messages.map(m => (
            m.role === 'user' ? (
              <UserMessage key={m.id} content={m.content} timestamp={m.timestamp} />
            ) : (
              <AssistantMessage key={m.id} message={m} />
            )
          ))
        )}
      </div>

      <div className="input-container">
        <Input.TextArea
          placeholder="输入你的问题，例如：请分析本项目的模块结构"
          autoSize={{ minRows: 1, maxRows: 6 }}
          value={input}
          onChange={e => setInput(e.target.value)}
          onPressEnter={(e) => {
            if (!e.shiftKey) {
              e.preventDefault();
              handleSend();
            }
          }}
        />
        {isStreaming ? (
          <Button icon={<StopOutlined />} onClick={stopStreaming} size="large">停止</Button>
        ) : (
          <Button type="primary" icon={<SendOutlined />} onClick={handleSend} size="large" disabled={!input.trim()}>发送</Button>
        )}
      </div>
    </div>
  );
};

export default AssistantTab;

